package org.hales.schedule;

import org.hales.dao.mpsql.CronJobMapper;
import org.hales.pojo.CronJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * 定时任务启动器
 * @author 陈建康
 */
//@Component
public class TaskLauncher {
//    @Autowired
    private CronJobMapper cronJobMapper;
//    @Autowired
    private TaskScheduler taskScheduler;
    private final Map<String, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TaskLauncher.class);
    @PostConstruct
    public void init() {
        log.info("初始化定时任务");
        // 获取任务配置
        List<CronJob> jobs = cronJobMapper.selectCronList(null, null);
        for (CronJob job : jobs) {
            if (job != null && job.getState() == 1) {
                String cronExpression = job.getCronExpression();
                Method method = null;
                try {
                    // 通过类的全路径获取 Class 对象
                    Class<?> clazz = Class.forName(job.getClassName());
                    method = clazz.getDeclaredMethod(job.getMethodName());
                } catch (ClassNotFoundException e) {
                    log.error("类【{}】，不存在，请检查", job.getClassName());
                } catch (NoSuchMethodException e) {
                    log.error("方法【{}】，不存在，请检查", job.getMethodName());
                }
                // 创建Runnable实例
                Method finalMethod = method;
                Runnable task = () -> {
                    try {
                        finalMethod.invoke(this);
                    } catch (Exception e) {
                        log.error("执行任务 {} 失败: {}", job.getJobName(), e.getMessage());
                    }
                };

                // 调度任务并存储调度结果
                scheduledTasks.put(job.getClassName(), taskScheduler.schedule(task, new CronTrigger(cronExpression)));
                log.info("定时任务【{}】已启动", job.getJobName());
            }
        }
        log.info("定时任务初始化完成,共计启动{}个任务", scheduledTasks.size());
    }
}
